package org.lucifer.message.hibernate.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.lucifer.message.hibernate.HibernateSessionFactory;
import org.lucifer.message.hibernate.dao.MessageDao;

import org.lucifer.message.hibernate.model.Message;

public class MessageDaoHibernate implements MessageDao {

	public void save(Message m) {
		Session session = HibernateSessionFactory.getSession();
        Transaction tx = session.beginTransaction();
        session.save(m);
        tx.commit();
        HibernateSessionFactory.closeSession();
	}

	public void delete(int id) {
		Session session = HibernateSessionFactory.getSession();
        Transaction tx = session.beginTransaction();
		String hql = "DELETE Message WHERE id="+id;
		Query q = session.createQuery(hql);
		q.executeUpdate();
		tx.commit();
        HibernateSessionFactory.closeSession();
	}

	public Message getMessage(Integer id) {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("rawtypes")
	public List getMessages() {
		Session session = HibernateSessionFactory.getSession();
        Transaction tx = session.beginTransaction();
        Query q=session.createQuery("select m from Message m");
        List l=q.list();
        tx.commit();
        HibernateSessionFactory.closeSession();
		return l;
	}

	@SuppressWarnings("rawtypes")
	public List getMessagesByKeyWord(String keyWord) {
		Session session = HibernateSessionFactory.getSession();
        Transaction tx = session.beginTransaction();
        Query q=session.createQuery("select m from Message m where m.description like '%"+keyWord+"%'");
        List l=q.list();
        tx.commit();
        HibernateSessionFactory.closeSession();
		return l;
	}

	public void update(Message m){
			Session session = HibernateSessionFactory.getSession();
        Transaction tx = session.beginTransaction();
        Query q=session.createQuery("update Message m set m.description='"+m.getDescription()+"',m.title='"+m.getTitle()+"' where m.id="+m.getId());
        q.executeUpdate(); 
        tx.commit();
        HibernateSessionFactory.closeSession();
	}

}
